package com.dlxy.controller;

import com.Kapicommon.exception.BusinessException;
import com.Kapicommon.exception.ErrorCode;
import com.Kapicommon.model.entity.User;
import com.Kapicommon.response.BaseResponse;
import com.Kapicommon.utils.ResponseUtil;
import com.dlxy.service.UserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
public class FileUploadController {

    @Resource
    private UserService userService;

    // 文件上传的请求映射路径
    @PostMapping("/upload")
    public BaseResponse<String> handleFileUpload(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"上传文件为空");
        }

        try {
            // 指定上传文件的保存路径
            String uploadDir = request.getServletContext().getRealPath("/uploads/");

            // 确保目录存在
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 获取文件名，并添加UUID防止文件名重复
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();

            // 保存文件到指定路径
            Path path = Paths.get(uploadDir + File.separator + fileName);
            Files.copy(file.getInputStream(), path);

            // 返回可以访问的URL
            String fileUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/api/uploads/" + fileName;
            User loginUser = userService.getLoginUser(request);
            long id = loginUser.getId();
            User user=new User();
            user.setUserAvatar(fileUrl);
            user.setId(id);
            userService.saveOrUpdate(user);
            System.out.println(fileUrl);
            return ResponseUtil.success(fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResponseUtil.success("上传成功");
    }
}
